package com.zeek.car90s;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.SoundPool;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.ads.mediation.admob.AdMobAdapter;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.game.UMGameAgent;
import com.zeek.car90s.util.DbHelper;
import com.zeek.car90s.util.MediaPlayerUtils;
import com.zeek.car90s.util.SoundPoolUtils;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

public class StartActivity extends AppCompatActivity {

    private Button btnStart, btnSign, btnSound, btnMore, btnContribute, btnExit;
    private SharedPreferences sp;
    private int storageDay;
    private int countSign;
    private static final int MAX_SIGN_COUNT = 1;
    private SoundPool soundPool;
    private HashMap<Integer, Integer> mapSRC;
//    RecommendAd recommendAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        SoundPoolUtils.init(this);
        MediaPlayerUtils.init(this);

        //初始化并预加载插屏
        Constants.mInterstitialAd = new InterstitialAd(this);
        Constants.mInterstitialAd.setAdUnitId(getString(R.string.insert_ad_unit_id));

        Constants.mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                requestNewInterstitial();
            }
        });
        requestNewInterstitial();

        //初始化并预加载激励视频
        Constants.rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
        Bundle extras = new Bundle();
        extras.putBoolean("_noRefresh", true);
        AdRequest adRequest = new AdRequest.Builder()
                .addNetworkExtrasBundle(AdMobAdapter.class, extras)
                .build();
        Constants.rewardedVideoAd.loadAd(getString(R.string.rewarded_ad_unit_id), adRequest);

        sp = getSharedPreferences(Constants.SHARED_PREFERENCE_PREFIX, Context.MODE_PRIVATE);
//        countSign = sp.getInt("count_sign", 0);
//        storageDay = sp.getInt("day", -1);
        Constants.CHECK_ANSWER_COUNT = sp.getInt("check_answer_count", 0);
        //默认背景音乐开关
        Constants.isPlayMusic = sp.getBoolean(Constants.IS_PLAY_MUSIC_PREFIX, false);
        Constants.TOTAL_COIN = sp.getInt(Constants.COIN_PREFIX, Constants.TOTAL_COIN_DEFAULT_VALUE);
        //读取并保存总关卡数
        Constants.TOTAL_LEVEL = sp.getInt(Constants.TOTAL_LEVEL_PREFIX, -1);
        if (Constants.TOTAL_LEVEL == -1) {
            SQLiteDatabase db = DbHelper.getDataBase(this);
            if (db != null) {
                String sql = "select count(*) as count from data;";
                Cursor cursor = db.rawQuery(sql, null);
                while (cursor.moveToNext()) {
                    Constants.TOTAL_LEVEL = cursor.getInt(cursor.getColumnIndex("count"));
                }
            }
            SharedPreferences.Editor editor = sp.edit();
            editor.putInt(Constants.TOTAL_LEVEL_PREFIX, Constants.TOTAL_LEVEL);
            editor.commit();
        }

//        Calendar cal = Calendar.getInstance();
//        int myDay = cal.get(Calendar.DATE);
//        if (myDay != storageDay) {
//            countSign = 0;
//            Constants.CHECK_ANSWER_COUNT = 0;
//            SharedPreferences.Editor editor = sp.edit();
//            editor.putInt("day", myDay);
//            editor.apply();
//        }

        //开始
        btnStart = (Button) findViewById(R.id.btn_start_game);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayerUtils.playNotification(1);
//                startActivity(new Intent(StartActivity.this, MapActivity.class));
                startActivity(new Intent(StartActivity.this, GameActivity.class));
            }
        });

        //挣金币
        btnSign = (Button) findViewById(R.id.btn_sign_in);
        btnSign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayerUtils.playNotification(1);
                startActivity(new Intent(StartActivity.this, EarnCoinsActivity.class));
                MobclickAgent.onEvent(StartActivity.this, "earn_coin_from_main");

//                //每日签到
//                if (countSign < MAX_SIGN_COUNT) {
//                    Constants.TOTAL_COIN = sp.getInt(Constants.COIN_PREFIX, 0);
//                    Constants.TOTAL_COIN += 50;
//                    Toast.makeText(StartActivity.this, R.string.get_coin_hint, Toast.LENGTH_SHORT).show();
//
//                    SoundPoolUtils.play(1);
//
//                    countSign++;
//                    SharedPreferences.Editor editor = sp.edit();
//                    editor.putInt("count_sign", countSign);
//                    editor.putInt(Constants.COIN_PREFIX, Constants.TOTAL_COIN);
//                    editor.apply();
//                } else {
//                    Toast.makeText(StartActivity.this, R.string.has_signed_hint, Toast.LENGTH_SHORT).show();
//                }
            }
        });

        //声音
        btnSound = (Button) findViewById(R.id.btn_sound);
        btnSound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Constants.isPlayMusic) {//关闭声音
                    Constants.isPlayMusic = false;
                    MediaPlayerUtils.pause();
                    btnSound.setText(R.string.music_off);
                    MobclickAgent.onEvent(StartActivity.this, "music_off");
                } else {//打开声音
                    Constants.isPlayMusic = true;
                    MediaPlayerUtils.play();
                    btnSound.setText(R.string.music_on);
                    MobclickAgent.onEvent(StartActivity.this, "music_on");
                }
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean(Constants.IS_PLAY_MUSIC_PREFIX, Constants.isPlayMusic);
                editor.commit();
            }
        });
        if (Constants.isPlayMusic) {
            btnSound.setText(R.string.music_on);
        } else {
            btnSound.setText(R.string.music_off);
        }

        //更多
        btnMore = (Button) this.findViewById(R.id.btn_more);
        btnMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayerUtils.playNotification(1);
                //在Google Play中打开ZeekDev的全部APP
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/developer?id=ZeekDev")));
                MobclickAgent.onEvent(StartActivity.this, "more_game_click");
            }
        });

        //退出
        btnExit = (Button) findViewById(R.id.btn_exit);
        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayerUtils.pause();
                finish();
            }
        });

        if (Constants.isPlayMusic) {
            MediaPlayerUtils.play();
        }

        //友盟统计
        UMGameAgent.init(this);
        MobclickAgent.updateOnlineConfig(this);

        MobclickAgent.onEvent(this, "start_activity");
    }

    @Override
    protected void onResume() {
        super.onResume();
        UMGameAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        UMGameAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //预加载插屏广告
    private void requestNewInterstitial() {
        AdRequest adRequest = new AdRequest.Builder()
                .build();

        Constants.mInterstitialAd.loadAd(adRequest);
    }

    /**
     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click(); //调用双击退出函数
        }
        return false;
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, R.string.double_click_exit, Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            finish();
            System.exit(0);
        }
    }
}
